package com.xzakota.minesweeper.widget;

import com.xzakota.minesweeper.model.GameModel;
import com.xzakota.minesweeper.model.Observable;
import com.xzakota.minesweeper.model.Observer;
import com.xzakota.minesweeper.model.entity.CellBean;

import javax.swing.*;
import java.awt.*;

/**
 * 游戏格子矩阵视图，即包含所有格子的主体视图
 *
 * @author Xzakota
 */
public class GameCellMapPanel extends JPanel implements Observer {
    private CellBean[][] allCells;

    public GameCellMapPanel(GameModel model) {
        this.setOpaque(false);
        this.setBorder(BorderFactory.createLoweredSoftBevelBorder());
        model.addObserver(this);
    }

    @Override
    public void update(Observable o, Object arg) {
        GameModel status = (GameModel) o;
        if (status.allCells != this.allCells) {
            changeLayout(status);
        }
    }

    private void changeLayout(GameModel status) {
        this.removeAll();
        // GameLevel level = status.currentGameLevel;
        CellBean[][] allCells = status.allCells;
        this.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(0, 0, 0, 0);
        CellLabel cell;
        for (int y = 0; y < allCells.length; y++) {
            for (int x = 0; x < allCells[y].length; x++) {
                cell = new CellLabel(allCells[y][x]);
                gbc.gridx = x;
                gbc.gridy = y;
                this.add(cell, gbc);
            }
        }
        this.revalidate();
        this.repaint();
        this.allCells = status.allCells;
    }
}
